package com.bjsj.pro.tools;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.bjsj.pro.R;
import com.bjsj.pro.view.SelectDialog;
import com.bjsj.pro.wxapi.EventPayCode;
import com.bjsj.pro.wxapi.WxPayData;
import com.chinaums.pppay.unify.UnifyPayPlugin;
import com.chinaums.pppay.unify.UnifyPayRequest;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;


public class Dialogutils
{

    //拍照提示框
    public static SelectDialog showDialog(SelectDialog.SelectDialogListener listener, Activity activity) {
        List<String> names = new ArrayList<>();
        names.add(activity.getString(R.string.selcertPaizhao));
        names.add(activity.getString(R.string.selcertXiangce));
        SelectDialog dialog = new SelectDialog(activity, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!activity.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    public static SelectDialog showSexDialog(SelectDialog.SelectDialogListener listener, Activity activity) {
        List<String> names = new ArrayList<>();
       // names.add(activity.getString(R.string.nan));
       // names.add(activity.getString(R.string.nv));
        SelectDialog dialog = new SelectDialog(activity, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!activity.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }


    /**
     * 生成微信支付参数
     */
    public static void startWxPay(Activity activity, WxPayData data)
    {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(activity, Configs.WX_APP_ID);
        PayReq req = new PayReq();
        req.appId = data.getAppid();
        req.partnerId = data.getPartnerid();
        req.prepayId = data.getPrepayid();
        req.packageValue = data.getPackages();
        req.nonceStr = data.getNoncestr();
        req.timeStamp = data.getTimestamp();
        req.sign = data.getSign();


        // 把参数的值传进去SortedMap集合里面
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", data.getAppid());
        parameters.put("noncestr", data.getNoncestr());
        parameters.put("package", data.getPackages());
        parameters.put("partnerid", data.getPartnerid());
        parameters.put("prepayid", data.getPrepayid());
        parameters.put("timestamp", data.getTimestamp());

        String characterEncoding = "UTF-8";
        String mySign = createSign(characterEncoding, parameters);

        req.sign = mySign;
         System.out.println("===================我的签名是：" + mySign+"---"+parameters.toString());
        boolean register = msgApi.registerApp(req.appId);
        if (!register)
        {
            EventBus.getDefault().post(new EventPayCode(-4));
            System.out.println("===================调用微信失败");

            return;
        }
        boolean sendReq = msgApi.sendReq(req);
        if (!sendReq)
        {
            EventBus.getDefault().post(new EventPayCode(-5));
            System.out.println("===================支付发起失败");
            return;
        }
    }


    /**
     * 微信支付签名算法sign
     * @param characterEncoding
     * @param parameters
     * @return
     */
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb.append("key=" + "7EDCECF5AE825E566C0D12F119D25F81");
        System.out.println("签名字符串:"+sb.toString());
        System.out.println("签名MD5未变大写：" + MD5Util.MD5Encode(sb.toString(), characterEncoding));
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    public static void payWx(Activity activity,String appPayResult){
        UnifyPayRequest msg=new UnifyPayRequest();
        msg.payChannel=UnifyPayRequest.CHANNEL_WEIXIN;
        msg.payData=appPayResult;
        UnifyPayPlugin.getInstance(activity).sendPayRequest(msg);
    }

    public static void payAlipaymini(Activity activity,String appPayResult){
        UnifyPayRequest msg=new UnifyPayRequest();
        msg.payChannel=UnifyPayRequest.CHANNEL_ALIPAY_MINI_PROGRAM;
        msg.payData=appPayResult;
        UnifyPayPlugin.getInstance(activity).sendPayRequest(msg);
    }

    public static void paycloudquickpay(Activity activity,String appPayResult){
        String tn="空";
        try {
            JSONObject jsonObject=new JSONObject(appPayResult);
            tn=jsonObject.getString("tn");
        } catch (JSONException e) {
           e.printStackTrace();
        }
        UPPayAssistEx.startPay(activity,null,null,tn,"00");
        Log.d("test","云闪付 tn="+tn);
    }

    public  static  void startxcx(Activity activity,String appPayResult){
        JSONObject json = null;
        try {
            json = new JSONObject(appPayResult);
            String miniuser = json.optString("miniuser");
            String minipath=json.optString("minipath");
            String appId =Constants.APP_ID ; // 填移动应用(App)的 AppId，非小程序的 AppID
            IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName =miniuser; // 填小程序原始id
            req.path = minipath;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
            api.sendReq(req);
        }catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public static void jumpAlipay(Activity context,String appPayResult) {
        JSONObject json = null;
        try {
            json = new JSONObject(appPayResult);
            String miniuser = json.optString("miniuser");
            String minipath=json.optString("minipath");
            String prepayid=json.optString("prepayid");
            String uri = "alipayqr://platformapi/startapp?appId="+miniuser
                    + "&page="+minipath//页面参数
                    + "&query="+prepayid;//启动参数
            Intent intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
